package cn.chengpengper.shortlink.service.impl;

import cn.chengpengper.shortlink.constant.RedisKeyTemplate;
import cn.chengpengper.shortlink.constant.ShortLinkConstant;
import cn.chengpengper.shortlink.enums.SendCodeEnum;
import cn.chengpengper.shortlink.service.CaptchaService;
import cn.chengpengper.shortlink.util.RedisKeyUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author huchengpeng
 * @version v1.0.0
 * @date 2023/8/21 00:20
 * @description 验证码服务实现
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private Producer captchaProducer;

    @Override
    public void getImageCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String text = captchaProducer.createText();
        // 存储redis,设置过期时间为5min
        redisTemplate.opsForValue()
                .set(RedisKeyUtil.getCaptchaKey(RedisKeyTemplate.ACCOUNT_CAPTCHA_KEY, request), text, 5, TimeUnit.MINUTES);

        BufferedImage image = captchaProducer.createImage(text);

        try (ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("获取流出错:{}", e.getMessage());
        }
    }

    @Override
    public boolean captchaVerify(SendCodeEnum type, String to, String code) {
        String cacheKey = String.format(RedisKeyTemplate.CHECK_CODE_KEY, type.name(), to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isBlank(cacheValue)) {
            return false;
        }

        String cacheCode = cacheValue.split(ShortLinkConstant.UNDERLINE)[0];
        if (!cacheCode.equalsIgnoreCase(code)) {
            return false;
        }
        redisTemplate.delete(cacheKey);
        return true;
    }
}
